//
//  HomeViewController.m
//  SinaWeibo
//
//  Created by Apple on 16/8/6.
//  Copyright © 2016年 Apple. All rights reserved.
//

#import "HomeViewController.h"
#import "ScanViewController.h"
#import "TitleButton.h"
#import "PopMeumView.h"
#import "MenuContentTableViewController.h"
#import "AcountModel.h"
#import "StatuesModel.h"
#import "UserModel.h"
#import "pictureModel.h"
#import "WeiboCell.h"
#import "WeiboFrameModel.h"
#import "XWeiboCell.h"


@interface HomeViewController ()

@property (strong, nonatomic) NSMutableArray *statusesData;

@property (weak, nonatomic) UIRefreshControl *refresh;


@end


@implementation HomeViewController

#pragma mark - dataArray懒加载
-(NSMutableArray *)statusesData{
    
    if (_statusesData == nil) {
        _statusesData = [NSMutableArray array];
    }
    return _statusesData;
}

-(void)viewWillAppear:(BOOL)animated{
    
    [super viewWillAppear:animated];
    
    if (self.defaultCenterView != nil) {
        [self.defaultCenterView starRotate];
    }
    
}

-(void)viewWillDisappear:(BOOL)animated{
    
    [super viewWillDisappear:animated];
    
    if (self.defaultCenterView != nil) {
        [self.defaultCenterView stopRotate];
    }
    
    
}

- (void)viewDidLoad {
    [super viewDidLoad];
    
    self.tableView.separatorStyle = UITableViewCellSeparatorStyleNone;
    
    //sb不用注册
    //    [self.tableView registerNib:[UINib nibWithNibName:@"XWeiboCell" bundle:nil] forCellReuseIdentifier:@"homeCell"];
#pragma mark ----- 设置导航蓝左右按钮
    //1.设置导航蓝
    [self setupNav];
    
    //2.设置默认注册登录界面/首页界面
    if (self.defaultCenterView != nil) {
        self.defaultCenterView.iconImageName = @"visitordiscover_feed_image_house";
        self.defaultCenterView.info = @"首页";
    }else{
        //2.1.加载用户信息
        [self setupUesrInfo];
        
        //2.2.获取当前登录用户及其所关注用户的最新微博/获取成功后将数据保存
        [self loadStatues];
        //2.3添加上下拉刷新
        [self setupRefresh];
        
    }
    
    [NSTimer scheduledTimerWithTimeInterval:60 target:self selector:@selector(getUnRead) userInfo:nil repeats:YES];
    
}

-(void)getUnRead{
    
    MyNetworkTools *tools = [MyNetworkTools shareManger];
    
    [tools getUnreadSuccess:^(NSString *badgeValue) {
        if (badgeValue.integerValue > 0) {
            [self.tabBarItem setBadgeValue:badgeValue];
        }
    } failure:^(NSError *error) {
        NSLog(@"获取未读数失败");
    }];
    
}

#pragma mark - 加载微博数据
-(void)setupRefresh{

    
    
//    [self.tableView addFooterWithTarget:self action:@selector(loadMreoStatuses)];
//    
//    [self.tableView addHeaderWithTarget:self action:@selector(loadNewStatus)];
    
 

    
    self.tableView.mj_header = [MJRefreshNormalHeader headerWithRefreshingTarget:self refreshingAction:@selector(loadNewStatus)];
    
    self.tableView.mj_footer = [MJRefreshAutoNormalFooter footerWithRefreshingTarget:self refreshingAction:@selector(loadMreoStatuses)];

    
    
    
}
//加载以前数据
-(void)loadMreoStatuses{
    
    MyNetworkTools *tools = [MyNetworkTools shareManger];
    
    NSString *maxId = [self.statusesData.lastObject idstr];
    
    [tools getNewStatuesWithMax_id:maxId Success:^(NSArray *statues) {
        
        //2.将数组添加到原有数组中
        [self.statusesData addObjectsFromArray:statues];
        
        //3.刷新列表
        [self.tableView reloadData];
        
        //  停止刷新
//        [self.tableView.tableFooterView footerEndRefreshing];
        [self.tableView.mj_footer endRefreshing];

    } failure:^(NSError *error) {
        
//        [self.tableView footerEndRefreshing];
        [self.tableView.mj_footer  endRefreshing];
        NSLog(@"加载更多失败");
        
    }];
    
    
        
    
    
}
//加载新数据

-(void)loadNewStatus{
    
    MyNetworkTools *tools = [MyNetworkTools shareManger];
    
    NSString *sinceID = [self.statusesData.firstObject idstr];
    
    [tools getNewStatuesWithSince_id:sinceID Success:^(NSArray *statues) {
        
        //2.将数组添加到原有数组中
        
        NSRange range = NSMakeRange(0, statues.count);
        
        NSIndexSet *indexSet = [NSIndexSet indexSetWithIndexesInRange:range];
       
        [self.statusesData insertObjects:statues atIndexes:indexSet];
        
        //3.刷新列表
        [self.tableView reloadData];
        
        //4.清空提醒按钮
        self.tabBarItem.badgeValue = nil;
        
        //5.停止刷新
//        [self.tableView headerEndRefreshing];
        [self.tableView.mj_header endRefreshing];
        
        //4.显示刷新了多少条数据
        [self showNewLoadwithCount:statues.count];
    } failure:^(NSError *error) {
//        [self.tableView headerEndRefreshing];
        [self.tableView.mj_header endRefreshing];
        NSLog(@"刷新失败");
    }];

    
}

//第一次加载数据
-(void)loadStatues{
    
    MyNetworkTools *tools = [MyNetworkTools shareManger];
    
    [tools getStatuesSuccess:^(NSArray *statues) {
        
        [self.statusesData addObjectsFromArray:statues];
        
        //3.2保存后刷新列表
        [self.tableView reloadData];
        
        //4显示更新了多少天数据
//        [self showNewLoadwithCount:statues.count];
    } failure:^(NSError *error) {
        
        NSLog(@"首页获取失败%@",error);
        
    }];
    
}

-(void)showNewLoadwithCount:(NSUInteger )count{
    //创建label
    UILabel *label = [[UILabel alloc]init];
    
    //设置frame
    CGFloat labelW = self.view.frame.size.width ;
    CGFloat labelH = 25 ;
    CGFloat labelX = 0 ;
    CGFloat labelY = 64 - labelH ;
    label.frame = CGRectMake(labelX, labelY, labelW, labelH);
    label.alpha = 0;
    //设置label内容
    label.text = [NSString stringWithFormat:@"更新了%tu条微博",count];
    label.textAlignment = NSTextAlignmentCenter;
    label.backgroundColor = [UIColor orangeColor];
    
    //插入到导航条后面
    [self.navigationController.view insertSubview:label belowSubview:self.navigationController.navigationBar];
    
    //动画弹出，延迟消失
    [UIView animateWithDuration:1 animations:^{
        label.alpha = 1;
        label.transform = CGAffineTransformMakeTranslation(0, label.frame.size.height);
    } completion:^(BOOL finished) {
        [UIView animateWithDuration:1 delay:1.5 options:0 animations:^{
            label.alpha = 0;
            label.transform = CGAffineTransformIdentity;
        } completion:^(BOOL finished) {
            [label removeFromSuperview];
        }];
    }];
    
    
}

-(void)setupUesrInfo{
    
    
    MyNetworkTools *tools = [MyNetworkTools shareManger];
    
    [tools getUserinfoSuccess:^(UserModel *user) {
        
        NSLog(@"用户访问成功");
        
        NSString *profile_image_url = user.profile_image_url;
        
        AcountModel *acountModel = [AcountModel acountModelFromSandbox];
        
        if ([acountModel.profile_image_url isEqualToString:profile_image_url]) {
            
            return;
        }else{
            acountModel.profile_image_url = profile_image_url;
            
            [acountModel saveModel];
        }
        
    } failure:^(NSError *error) {
        NSLog(@"用户访问失败-%@",error);
    }];
    
    
    
    
}

-(void)setupNav{
    
    self.navigationItem.leftBarButtonItem = [UIBarButtonItem setNavItemWithImageName:@"navigationbar_friendsearch" target:self  action:@selector(searchFriend)];
    self.navigationItem.rightBarButtonItem =[UIBarButtonItem setNavItemWithImageName:@"navigationbar_pop" target:self action:@selector(scan)];
    
    //设置标题的文字以及图片
    TitleButton *titleButton = [[TitleButton alloc]init];
    
    [titleButton sizeToFit];
    //调整titlelabel 和 imageView的位置。
#warning 如果在这里设置，button已经加载完系统默认的，所以要重写button的layOutSubviews来加载;
    [titleButton addTarget:self action:@selector(clickTitleButton:) forControlEvents:UIControlEventTouchUpInside];
    
    self.navigationItem.titleView = titleButton;
    
}

-(void)clickTitleButton:(UIButton *)titleButton{
    //1.改变按钮状态
    titleButton.selected = !titleButton.selected;
    
    //2.弹出分组框
    MenuContentTableViewController *groupTableVC = [[MenuContentTableViewController alloc]init];
    groupTableVC.view.frame = CGRectMake(0, 0, 200, 300);
    groupTableVC.view.backgroundColor = [UIColor clearColor];
    
    
    //3.弹出下拉菜单
    [PopMeumView popFrom:titleButton contentVC:groupTableVC dissmissBlock:^{
        titleButton.selected = !titleButton.selected;
    }];
    
}

#pragma mark ---- 导航栏左右按钮的事件
-(void)searchFriend{
    
    NSLog(@"searchFri");
    
}

-(void)scan{
    
    
    
    UIStoryboard *storyboard = [UIStoryboard storyboardWithName:@"ScanViewController" bundle:nil];
    
    ScanViewController *scanVc = storyboard.instantiateInitialViewController;
    
    
    [self presentViewController:scanVc animated:YES completion:^{
        NSLog(@"present完成");
    }];
}

#pragma mark ------设置导航栏左右控件的方法.
- (void)didReceiveMemoryWarning {
    [super didReceiveMemoryWarning];
    // Dispose of any resources that can be recreated.
}


#pragma mark - Table view data source

- (NSInteger)numberOfSectionsInTableView:(UITableView *)tableView {
    
    return 1;
}

- (NSInteger)tableView:(UITableView *)tableView numberOfRowsInSection:(NSInteger)section {
    
    return self.statusesData.count;
}

- (UITableViewCell *)tableView:(UITableView *)tableView cellForRowAtIndexPath:(NSIndexPath *)indexPath {
    
    //1.创建cell
    static NSString *identifier = @"homeCell";
    
    
    //xib
    //    XWeiboCell *cell = [tableView dequeueReusableCellWithIdentifier:identifier];
    
    //sb
    XWeiboCell *cell = [tableView dequeueReusableCellWithIdentifier:identifier forIndexPath:indexPath];
    
    StatuesModel *statues = self.statusesData[indexPath.row];
    
    cell.statuesModel = statues;
    
    //3.返回cell
    return cell;
}

-(CGFloat)tableView:(UITableView *)tableView heightForRowAtIndexPath:(NSIndexPath *)indexPath{
    
    XWeiboCell *cell = [self.tableView dequeueReusableCellWithIdentifier:@"homeCell"];
    
    return [cell cellHeightWithStatu:self.statusesData[indexPath.row]];
    
}


@end
